import { useRef, useState } from 'react';

import { useControllableValue, useCountDown, useRequest } from 'ahooks';
import { Button, Input, InputProps, Space } from 'antd';
import cs from 'classnames';

import { store } from '@/store';

import Captcha, { CaptchaRef } from '../captcha';
import styles from './index.module.scss';

/**
 * 验证码输入框
 */
export type CodeInputProps = InputProps & {
  /** 获取验证码 */
  getCode: (captchaVerification: string) => Promise<unknown>;
  /** 获取验证码间隔时间，单位：秒 */
  interval?: number;
  /** 获取验证码成功回调 */
  onCodeSuccess?: () => void;
  buttonDisabled?: boolean;
};

const CodeInput: React.FC<CodeInputProps> = ({
  getCode: getCodeAsync,
  interval = 60,
  onCodeSuccess,
  className,
  buttonDisabled,
  ...rest
}) => {
  const captcha = useRef<CaptchaRef>(null);
  const [value, setValue] = useControllableValue<CodeInputProps['value']>(rest, {});
  const [targetDate, setTargetDate] = useState<number>();
  const [countdown] = useCountDown({
    targetDate,
    interval: 1000
  });
  // 获取验证码
  const code = useRequest(
    async (captchaVerification: string) => {
      await getCodeAsync(captchaVerification);

      store.app?.message?.success('验证码发送成功');

      setTargetDate(Date.now() + interval * 1000);
    },
    {
      manual: true,
      onSuccess: onCodeSuccess
    }
  );

  const onChange: InputProps['onChange'] = (e) => {
    setValue(e.target.value);
  };

  const disabled = code.loading || countdown !== 0 || buttonDisabled;

  const getCode = () => {
    captcha.current?.open({
      validSuccess(res) {
        code.run(res.data.id);
      }
    });
  };

  return (
    <>
      <Space.Compact
        className={cs(styles['search-input-wrapper'], {
          [styles['open']]: open
        })}
      >
        <Input
          className={cs(styles['search-input'], className)}
          allowClear
          {...rest}
          value={value}
          onChange={onChange}
        />
        <Button
          className={styles['get-code-btn']}
          type="primary"
          loading={code.loading}
          disabled={disabled}
          onClick={getCode}
        >
          {countdown === 0 ? '获取验证码' : `重发(${Math.round(countdown / 1000)}s)`}
        </Button>
      </Space.Compact>

      <Captcha ref={captcha} />
    </>
  );
};

export default CodeInput;
